package com.gombe.credit.app.ui.fragment

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import androidx.core.net.toUri
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonFragment
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.ActGombeCreditApplyDetailsChildItemBinding
import com.gombe.credit.app.databinding.FragmentGombeCreditRepayBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.activity.ActGombeCreditPayStatus
import com.gombe.credit.app.ui.dialog.DialogGombeCreditTips
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.helper.GombeCreditProcessHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONObject
import java.math.BigDecimal

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/12/10 14:53
 * @Annotation：待还款
 */
class FragmentGombeCreditRepay : CommonFragment() {
    private var _binding: FragmentGombeCreditRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit reapy binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //公告提示
    private var noticeDialog: DialogGombeCreditTips? = null

    override fun takeGombeCreditRootView(inflater: LayoutInflater): View {
        _binding = FragmentGombeCreditRepayBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        setGombeCreditRootParentBackgroundColor(getColor(R.color.white))
        _binding?.repayTitleBarLayout?.setPadding(0, GombeCreditTitleBarUtil.getStatusBarHeight() + GombeCreditDensityUtil.dp2px(10f), 0, 0)
        _binding?.repayPageRefreshLayout?.setColorSchemeResources(R.color.theme, R.color.purple_500)
    }

    override fun initGombeCreditListener() {
        _binding?.imgCustomer?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog("Repay Page")
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,"Repay Page")
            }
        })
        _binding?.repayPageRefreshLayout?.setOnRefreshListener {
            publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
        }
        _binding?.btnRepay?.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_REPAY,"Repay Page")
                // TODO: 还款按钮 需上报所有埋点
                GombeCreditPointManager.getInstance().manualReport()

                onGombeCreditPayAction()
            }
        })
    }

    override fun takeGombeCreditData() {
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_REPAY_START)
    }

    /**
     * 设置还款信息
     */
    private fun showGombeCreditRepayInfo(data: JSONObject){
        showGombeCreditNoticeDialog()
        _binding?.let { binding ->
            binding.textTotalRepayment.text = BigDecimal(data.optString("repayAmount")).stripTrailingZeros().toPlainString()
            binding.textCurrency.text = data.optString("currency")
            binding.textRepayDate.text = data.optString("repayDate")

            //逾期天数
            val overdueDay = data.optInt("overdueDay",0)
            if (overdueDay > 0){//已逾期 - 逾期天数
                binding.textRepayDueDate.text = String.format(getString(R.string.gombe_credit_repay_days_overdue),"$overdueDay")
                binding.textRepayDueDate.shapeDrawableBuilder
                    .setSolidColor(getColor(R.color.gombe_credit_FFFE4E33))
                    .intoBackground()
                binding.imageLeftTopCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_overdue_corner)
                binding.imageRightBottomCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_overdue_corner)
            } else {//未逾期 - 剩余还款天数
                binding.textRepayDueDate?.text = String.format(getString(R.string.gombe_credit_repay_days_left), data.optString("remainDay"))
                binding.textRepayDueDate.shapeDrawableBuilder
                    .setSolidColor(getColor(R.color.gombe_credit_FFFF9326))
                    .intoBackground()
                binding.imageLeftTopCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_left_corner)
                binding.imageRightBottomCorner.setImageResource(R.mipmap.gombe_credit_image_repay_days_left_corner)
            }

            binding.repayItemListLayout.removeAllViews()
            val detailItemList = data.optJSONArray("detailItemList")
            detailItemList?.let { itemList ->
                for (i in 0..< itemList.length()){
                    val childItem = itemList.optJSONObject(i)
                    val childView = ActGombeCreditApplyDetailsChildItemBinding.inflate(layoutInflater)
                    childView.textDetailsTitle.text = childItem.optString("showName")
                    childView.textDetailsTitle.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
                    childView.textDetailsValue.text = childItem.optString("showDetail")
                    childView.textDetailsValue.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))

                    childView.textOldValue.visibility = View.GONE
                    if (childItem.has("oldDetail")){
                        childView.textOldValue.visibility = View.VISIBLE
                        childView.textOldValue.text = childItem.optString("oldDetail")
                    }
                    childView.discountLayout.visibility = View.GONE
                    if (childItem.has("discount")){
                        childView.discountLayout.visibility = View.VISIBLE
                        childView.textDiscount.text = childItem.optString("discount")
                    }

                    childView.viewLine.visibility = View.VISIBLE
                    if (i == itemList.length() - 1){
                        childView.viewLine.visibility = View.GONE
                    }

                    binding.repayItemListLayout.addView(childView.root)
                }
            }
        }
    }

    /**
     * 链接还款
     */
    private fun showGombeCreditPayLink(linkUrl: String){
        val uri = linkUrl.toUri()
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * pin还款
     */
    private fun showGombeCreditPayStatusAction(thirdOrderId: String){
        ActGombeCreditPayStatus.start(requireContext(),thirdOrderId,binding.textRepayDate.text.toString())
    }

    /**
     * 公告提示
     */
    private fun showGombeCreditNoticeDialog(){
        // 检查是否可以显示公告提示 || 确保页面没有关闭
        if (!isGombeCreditShowNoticeDialog() || !isGombeCreditActive()) {
            return
        }

        val noticeInfo = GombeCreditConfigsHelper.takeGombeCreditNoticeInfo() ?: return
        // 更新显示次数
        GombeCreditConfigsHelper.showGombeCreditNoticeCount += 1
        noticeDialog = DialogGombeCreditTips(requireContext(),"Repay Page",object : DialogGombeCreditTips.IDialogCallback{
            override fun onClick(view: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.NOTICE_CONFIRM,"Repay Page")
            }
        })
        noticeDialog?.let { dialog ->
            dialog.setCancelable(true)
            dialog.setCanceledOnTouchOutside(true)
            dialog.show()
            dialog.isGombeCreditKindTipsDoubleButton(false)
            dialog.setGombeCreditKindTipsTitleText(noticeInfo.optString("noticeTitle"))
            dialog.setGombeCreditKindTipsMsgText(noticeInfo.optString("noticeText"))
            dialog.setGombeCreditKintTipsButtonConfirmText(getString(R.string.gombe_credit_button_confirm))
        }
    }

    /**
     * 检查是否应该显示通知对话框
     */
    private fun isGombeCreditShowNoticeDialog(): Boolean {
        if (!GombeCreditConfigsHelper.isGombeCreditNoticeShow()) {
            return false
        }

        val noticeInfo = GombeCreditConfigsHelper.takeGombeCreditNoticeInfo() ?: return false
        val showNum = noticeInfo.optInt("num", 1)
        val num = GombeCreditConfigsHelper.showGombeCreditNoticeCount

        if (num >= showNum) {
            return false
        }
        // 检查对话框是否已经在显示
        if (noticeDialog?.isShowing == true) {
            return false
        }
        return true
    }

    /**
     * 检查 Fragment 是否处于活跃状态
     */
    private fun isGombeCreditActive(): Boolean {
        return isAdded &&
                !isDetached &&
                activity != null &&
                !requireActivity().isFinishing &&
                !requireActivity().isDestroyed
    }

    /**
     * 获取还款信息
     */
    private fun loadGombeCreditRepayInfoAction(){
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_REPAYMENT_INFO_PATH)
            put("oldFlag","YES")
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    showGombeCreditRepayInfo(it)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 订单还款
     * 不减免 normal
     * 积分减免 score
     * 优惠券减免 coupon
     */
    private fun onGombeCreditPayAction(){
        showGombeCreditLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("mobile", GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_MOBILE))
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_REPAYMENT_MARKET_URL_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideGombeCreditLoading()
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    var linkUrl = obj.optString("url","")
                    if (linkUrl.isEmpty()){
                        linkUrl = obj.optString("repayUrl","")
                    }
                    //没有还款链接 - 需要进入还款状态页查询还款状态
                    if (linkUrl.isEmpty()){
                        val thirdOrderId = obj.optString("thirdOrderId")
                        if (thirdOrderId.isEmpty()){
                            showGombeCreditToast("Transaction id is empty")
                            return
                        }
                        showGombeCreditPayStatusAction(thirdOrderId)
                    } else {
                        showGombeCreditPayLink(linkUrl)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        when(event.eventType){
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED,
            GombeCreditEventData.TYPE.GOMBECREDIT_DATA_REFRESH -> {//收到刷新数据通知
                //待还款
                val isRepay = GombeCreditProcessHelper.isGombeCreditRepay()
                if (isRepay){
                    loadGombeCreditRepayInfoAction()
                }
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_NET_ERROR -> {
                hideGombeCreditLoading()
            }
            else -> {
            }
        }
    }

    override fun hideGombeCreditLoading() {
        super.hideGombeCreditLoading()
        _binding?.repayPageRefreshLayout?.isRefreshing = false
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_REPAY_END)
        // TODO: 待还款关闭 需上报所有埋点
        GombeCreditPointManager.getInstance().manualReport()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}